package com.cmcc.qx.ws.controller;

import java.io.IOException;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.cmcc.qx.common.Constants;
import com.cmcc.qx.common.entity.Article;
import com.cmcc.qx.util.HttpUtil;
import com.cmcc.qx.util.JsonUtil;
import com.cmcc.qx.util.PageUtil;
import com.cmcc.qx.ws.service.ArticleService;

@Controller
public class ArticleController {

	private static final Logger logger = Logger
			.getLogger(ArticleController.class);

	private static final int limit = Constants.limit;//每页显示的文章数
	@Resource(name = "ArticleServiceImpl")
	private ArticleService articleService;

	/**
	 * 加载类型
	 * @param type
	 * @param page
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "main/{type}/{page}/query.do", method = RequestMethod.GET)
	public String main(@PathVariable String type,@PathVariable int page,HttpServletRequest request, HttpServletResponse response) {
		List<Article> artTop = articleService.queryTop();
		int start = (page - 1)*limit;
		List<Article> arts = articleService.queryByType(start,limit, Integer.valueOf(type));
		request.setAttribute("artTop", artTop);
		request.setAttribute("arts", arts);
		
		int cnt = articleService.queryCnt(Integer.valueOf(type));
		Set<Integer> index = PageUtil.paginate(cnt, limit, page);
		int endnum = cnt/limit;
		if(cnt%limit>0){
			endnum++;
		}
		//分页
		request.setAttribute("index", index);
		request.setAttribute("endnum", endnum);
		request.setAttribute("type", type);
		request.setAttribute("page", page);
		
		return "/index.jsp";
	}
	
	/**
	 * 加载分类的导航文章
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "guide.do", method = RequestMethod.GET)
	public void guide(HttpServletRequest request, HttpServletResponse response) {
		String start = request.getParameter("start");
		if("".equals(start)||start==null){
			start = "0";
		}
		String limit = request.getParameter("limit");
		if("".equals(limit)||limit==null){
			limit = "10";
		}
		String type = request.getParameter("type");
		JSONObject jsonObject = new JSONObject();
		List<Article> artTop = articleService.queryTop();
		List<Article> arts = articleService.queryByType(Integer.valueOf(start),
				Integer.valueOf(limit), Integer.valueOf(type));
		// 排行文章（按照访问量排序）
		List<Article> artRank = articleService.queryRank();
		try {
			if (artTop != null) {
				JSONArray jsonarray = JsonUtil.fromObject(artTop);
				jsonObject.put("artTop", jsonarray);
			} else {
				logger.warn("人工前五名文章记载为空！！！");
			}
			if (arts != null) {
				JSONArray array = JsonUtil.fromObject(arts);
				jsonObject.put("arts", array);
				logger.info("json = " + jsonObject.toString());
			} else {
				logger.warn("分类文章加载失败");
			}
			if (artRank != null) {
				JSONArray jsonarray = JsonUtil.fromObject(artRank);
				jsonObject.put("artRank", jsonarray);
			} else {
				logger.warn("按访问量文章加载为空");
			}
			HttpUtil.print(response, jsonObject.toString());
		} catch (Exception e) {
			logger.error("分类文章加载失败");
		}
	}
	/**
	 * 加载首页右半部分的热门文章等其他模块
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "right.do",method = RequestMethod.GET)
	public void queryRight(HttpServletRequest request, HttpServletResponse response) throws IOException{
		try {
			List<Article> rank = articleService.queryRank();
			List<String> tags = articleService.queryTag();
			JSONObject jsonObject = new JSONObject();
			JSONArray jsonarray = JsonUtil.fromObject(rank);
			jsonObject.put("artRank", jsonarray);
			logger.info("tags="+tags);
			jsonObject.put("tags", tags);
			HttpUtil.print(response, jsonObject.toString());
		} catch (Exception e) {
			logger.error("",e);
			response.sendError(500);
		}
	}
	
	/**
	 * 查询标签
	 * @param tag
	 * @param page
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/tag/{tag}/{page}/query.do", method= RequestMethod.GET)
	public String queryTag(@PathVariable String tag,@PathVariable int page, HttpServletRequest request, HttpServletResponse response ) throws IOException{
		int start = (page - 1)*limit;
		tag = new String(tag.getBytes("iso8859-1"),"UTF-8");
		List<Article> tagsArt = articleService.queryTagArt(start, limit, tag);
		request.setAttribute("arts", tagsArt);
		int cnt = articleService.queryTagArtCnt(tag);
		logger.info("cnt" + cnt);
		Set<Integer> index = PageUtil.paginate(cnt, limit, page);
		int endnum = cnt/limit;
		if(cnt%limit!=0){
			endnum++;
		}
		logger.info("!!!!!!!!!!!!!"+cnt%limit);
		request.setAttribute("index", index);
		request.setAttribute("endnum", endnum);
		request.setAttribute("page", page);
		return "/index.jsp";
	}
	
	@RequestMapping(value = "addvisit.do", method = RequestMethod.GET)
	public void addVisits(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String artid = request.getParameter("id");
		articleService.addVisits(artid);
	}
}
